//
//  WSDatePickerView.m
//  WSDatePicker
//
//  Created by iMac on 17/2/23.
//  Copyright © 2017年 zws. All rights reserved.
//

#import "EKDateTimePickerView.h"
#import "UIView+Addition.h"
#import "NSDate+ROCaculateTime.h"
#import "RODateHelper.h"
#import "NSDate+Extension.h"

#define kScreenWidth     [UIScreen mainScreen].bounds.size.width
#define kScreenHeight    [UIScreen mainScreen].bounds.size.height
#define kPickerSize      self.datePicker.frame.size
#define RGBA(r, g, b, a) ([UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a])
#define RGB(r, g, b)     RGBA(r,g,b,1)

#define MAXYEAR 2020
#define MINYEAR 2015
#define kROWNUMBER 10

typedef void(^doneBlock)(NSDate *);

@interface EKDateTimePickerView ()<UIPickerViewDelegate,UIPickerViewDataSource,UIGestureRecognizerDelegate> {
    //日期存储数组
    NSMutableArray *_yearArray    ;
    NSMutableArray *_monthArray   ;
    NSMutableArray *_dayArray     ;
    NSMutableArray *_hourArray    ;
    NSMutableArray *_minuteArray  ;
    NSString       *_dateFormatter;
    //记录位置
    NSInteger yearIndex  ;
    NSInteger monthIndex ;
    NSInteger dayIndex   ;
    NSInteger hourIndex  ;
    NSInteger minuteIndex;
    
    NSDate *_startDate;
    EKDatePickerPosition datePosition;
}
@property (weak, nonatomic) IBOutlet UIView             *containerView   ;
@property (weak, nonatomic) IBOutlet UILabel            *showYearView    ;
@property (weak, nonatomic) IBOutlet UIButton           *doneBtn         ;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraint  ;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightConstraint ;

// 确认按钮点击
- (IBAction)doneAction:(UIButton *)btn;

@property (nonatomic, strong) UIPickerView *datePicker;
@property (nonatomic, retain) NSDate *scrollToDate;//滚到指定日期
@property (nonatomic, strong) doneBlock doneBlock;


@end

@implementation EKDateTimePickerView

-(instancetype)initWithDatePosition:(EKDatePickerPosition)position CompleteBlock:(void(^)(NSDate *))completeBlock {
    
    self = [super init];
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] lastObject];
        datePosition   = position;
        _dateFormatter = @"yyyy-MM-dd HH:mm";
        [self setupUI];
        [self defaultConfig];
        
        if (completeBlock) {
            self.doneBlock = ^(NSDate *startDate) {
                completeBlock(startDate);
            };
        }
    }
    return self;
}

-(void)setupUI {
    self.containerView.layer.cornerRadius  = 10;
    self.containerView.layer.masksToBounds = YES;
    self.themeColor = RGB(247, 133, 51);
    self.frame      = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    switch (datePosition) {
        case 0:
            
            break;
        case 1:{
            self.leftConstraint.constant  = 16;
            self.rightConstraint.constant = 16;
        }
            break;
        default:
            break;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    self.bottomConstraint.constant = -self.height;
    [self layoutIfNeeded];
    
    self.backgroundColor = RGBA(0, 0, 0, 0);
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    [self.showYearView addSubview:self.datePicker];
}

-(void)defaultConfig {
    if (!_scrollToDate) {
        NSString *str = [[NSDate date] stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
        _scrollToDate = [RODateHelper dateWithOutTimeZoneFromString:str withFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    
    _yearArray   = [self setArray:_yearArray];
    _monthArray  = [self setArray:_monthArray];
    _dayArray    = [self setArray:_dayArray];
    _hourArray   = [self setArray:_hourArray];
    _minuteArray = [self setArray:_minuteArray];
    // 月 时 分
    NSMutableArray *tempMonArray  = [[NSMutableArray alloc] init];
    NSMutableArray *tempHourArray = [[NSMutableArray alloc] init];
    NSMutableArray *tempMinArray  = [[NSMutableArray alloc] init];
    for (int i=0; i<60; i++) {
        NSString *num = [NSString stringWithFormat:@"%02d",i];
        if (0<i && i<=12)
            [tempMonArray addObject:num];
        if (i<24)
            [tempHourArray addObject:num];
        [tempMinArray addObject:num];
    }
    for (int i = 0 ; i <= kROWNUMBER; i ++) {
        [_monthArray  addObjectsFromArray:tempMonArray ];
        [_hourArray   addObjectsFromArray:tempHourArray];
        [_minuteArray addObjectsFromArray:tempMinArray ];
    }
    
    NSMutableArray *tempYearArray = [[NSMutableArray alloc] init];
    for (NSInteger i=MINYEAR; i<MAXYEAR; i++) {
        NSString *num = [NSString stringWithFormat:@"%ld",(long)i];
        [tempYearArray addObject:num];
    }
    for (int i = 0 ; i <= kROWNUMBER ; i ++) {
        [_yearArray addObjectsFromArray:tempYearArray];
    }
    
    if (!self.maxLimitDate) {
//        self.maxLimitDate = [NSDate date:@"2049-12-31 23:59" WithFormat:@"yyyy-MM-dd HH:mm"];
        self.maxLimitDate = [RODateHelper dateFromString:@"2049-12-31 23:59" withFormat:@"yyyy-MM-dd HH:mm"];
    }
    
    if (!self.minLimitDate) {
        self.minLimitDate = [NSDate dateWithTimeIntervalSince1970:0];
    }
}

-(void)addLabelWithName:(NSArray *)nameArr {
    for (id subView in self.showYearView.subviews) {
        if ([subView isKindOfClass:[UILabel class]]) {
            [subView removeFromSuperview];
        }
    }
    for (int i=0; i<nameArr.count; i++) {
        CGFloat labelX = kPickerSize.width/(nameArr.count*2)+17+kPickerSize.width/nameArr.count*i;
        //NSLog(@"%f %f ",kPickerSize.width, labelX);
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(labelX, self.showYearView.frame.size.height/2-15/2.0, 15, 15)];
        label.text = nameArr[i];
        label.textAlignment   = NSTextAlignmentCenter;
        label.font            = [UIFont systemFontOfSize:14];
        label.textColor       = self.themeColor;
        label.backgroundColor = [UIColor clearColor];
        [self.showYearView addSubview:label];
    }
}

- (NSMutableArray *)setArray:(id)mutableArray {
    if (mutableArray)
        [mutableArray removeAllObjects];
    else
        mutableArray = [NSMutableArray array];
    return mutableArray;
}

#pragma mark - UIPickerViewDelegate,UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    switch (self.datePickerStyle) {
        case EKDateStyleShowYearMonthDayHourMinute:
            [self addLabelWithName:@[@"年",@"月",@"日",@"时",@"分"]];
            return 5;
        case EKDateStyleShowYearMonthDay:
            [self addLabelWithName:@[@"年",@"月",@"日"]];
            return 3;
        case EKDateStyleShowMonthDayHourMinute:
            [self addLabelWithName:@[@"月",@"日",@"时",@"分"]];
            return 4;
        case EKDateStyleShowMonthDay:
            [self addLabelWithName:@[@"月",@"日"]];
            return 2;
        case EKDateStyleShowHourMinute:
            [self addLabelWithName:@[@"时",@"分"]];
            return 2;
        default:
            return 0;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSArray *numberArr = [self getNumberOfRowsInComponent];
    return [numberArr[component] integerValue];
}

-(NSArray *)getNumberOfRowsInComponent {
    
    NSInteger yearNum      = _yearArray.count;
    NSInteger monthNum     = _monthArray.count;
    NSInteger dayNum       = [self DaysfromYear:[_yearArray[yearIndex] integerValue] andMonth:[_monthArray[monthIndex] integerValue]];
    NSInteger hourNum      = _hourArray.count;
    NSInteger minuteNUm    = _minuteArray.count;
    
    NSInteger timeInterval = MAXYEAR - MINYEAR;
    
    switch (self.datePickerStyle) {
        case EKDateStyleShowYearMonthDayHourMinute:
            return @[@(yearNum),@(monthNum),@(dayNum * kROWNUMBER),@(hourNum),@(minuteNUm)];
            break;
        case EKDateStyleShowMonthDayHourMinute:
            return @[@(monthNum*timeInterval),@(dayNum ),@(hourNum),@(minuteNUm)];
            break;
        case EKDateStyleShowYearMonthDay:
            return @[@(yearNum),@(monthNum),@(dayNum)];
            break;
        case EKDateStyleShowMonthDay:
            return @[@(monthNum*timeInterval),@(dayNum),@(hourNum)];
            break;
        case EKDateStyleShowHourMinute:
            return @[@(hourNum),@(minuteNUm)];
            break;
        default:
            return @[];
            break;
    }
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *customLabel = (UILabel *)view;
    if (!customLabel) {
        customLabel = [[UILabel alloc] init];
        customLabel.textAlignment = NSTextAlignmentCenter;
        [customLabel setFont:[UIFont systemFontOfSize:17]];
    }
    NSString *title;
    
    //    switch (self.datePickerStyle) {
    //        case DateStyleShowYearMonthDayHourMinute:
    if (component==0) {
        title = _yearArray[row];
    }
    if (component==1) {
        title = _monthArray[row];
    }
    if (component==2) {
        title = _dayArray[row];
    }
    if (component==3) {
        title = _hourArray[row];
    }
    if (component==4) {
        title = _minuteArray[row];
    }
    
    customLabel.text = title;
    customLabel.textColor = [UIColor blackColor];
    return customLabel;
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        yearIndex = row;
        
        self.showYearView.text =_yearArray[yearIndex];
    }
    if (component == 1) {
        monthIndex = row;
    }
    if (component == 2) {
        dayIndex = row;
    }
    if (component == 3) {
        hourIndex = row;
    }
    if (component == 4) {
        minuteIndex = row;
    }
    
    [pickerView reloadAllComponents];
    
    NSString *dateStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",_yearArray[yearIndex],_monthArray[monthIndex],_dayArray[dayIndex],_hourArray[hourIndex],_minuteArray[minuteIndex]];

    self.scrollToDate = [NSDate date:dateStr WithFormat:@"yyyy-MM-dd HH:mm"];
    
    if ([self.scrollToDate compare:self.minLimitDate] == NSOrderedAscending) {
        self.scrollToDate = self.minLimitDate;
        [self getNowDate:self.minLimitDate animated:YES];
    }else if ([self.scrollToDate compare:self.maxLimitDate] == NSOrderedDescending){
        self.scrollToDate = self.maxLimitDate;
        [self getNowDate:self.maxLimitDate animated:YES];
    }
    
    _startDate = self.scrollToDate;
    
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if( [touch.view isDescendantOfView:self.containerView]) {
        return NO;
    }
    return YES;
}

#pragma mark - Action
-(void)show {
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    if (datePosition == EKDatePositionMiddel) {
        [UIView animateWithDuration:.3 animations:^{
            self.bottomConstraint.constant = kScreenHeight / 2 - self.datePicker.height / 2;
            //NSLog(@"%f %f %f",self.bottomConstraint.constant, kScreenHeight, self.height);
            self.backgroundColor = RGBA(0, 0, 0, 0.4);
             [self layoutIfNeeded];
        }];
    }
    if (datePosition == EKDatePositionBottom) {
        [UIView animateWithDuration:.3 animations:^{
            self.bottomConstraint.constant = 10;
            self.backgroundColor = RGBA(0, 0, 0, 0.4);
            [self layoutIfNeeded];
        }];
    }
}

-(void)dismiss {
    [UIView animateWithDuration:.3 animations:^{
        self.bottomConstraint.constant = -self.height;
        self.backgroundColor = RGBA(0, 0, 0, 0);
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    }];
}

- (IBAction)doneAction:(UIButton *)btn {
    
    _startDate = [self.scrollToDate dateWithTimeZoneWithFormatter:_dateFormatter];
    
    self.doneBlock(_startDate);
    [self dismiss];
}

#pragma mark - 计算
//通过年月求每月天数
- (NSInteger)DaysfromYear:(NSInteger)year andMonth:(NSInteger)month {
    NSInteger num_year  = year;
    NSInteger num_month = month;
    
    BOOL isrunNian = num_year%4==0 ? (num_year%100==0? (num_year%400==0?YES:NO):YES):NO;
    switch (num_month) {
        case 1:case 3:case 5:case 7:case 8:case 10:case 12:{
            [self setdayArray:31];
            return 31;
        }
        case 4:case 6:case 9:case 11:{
            [self setdayArray:30];
            return 30;
        }
        case 2:{
            if (isrunNian) {
                [self setdayArray:29];
                return 29;
            }else{
                [self setdayArray:28];
                return 28;
            }
        }
        default:
            break;
    }
    return 0;
}

//设置每月的天数数组
- (void)setdayArray:(NSInteger)num {
    NSMutableArray *tempDayArray = [[NSMutableArray alloc] init];
    [_dayArray removeAllObjects];
    for (int i=1; i<=num; i++) {
        [tempDayArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    for (int i = 0; i <= kROWNUMBER; i ++) {
        [_dayArray addObjectsFromArray:tempDayArray];
    }
}

- (void) scrollToSepicefyDate:(NSDate *)date animated:(BOOL)animated {
    [self getNowDate:date animated:animated];
}

//滚动到指定的时间位置
- (void)getNowDate:(NSDate *)date animated:(BOOL)animated {
    if (date == nil) {
        date = [NSDate date];
    }else {
        _scrollToDate = date;
    }
    
    [self DaysfromYear:date.year andMonth:date.month];
    
    yearIndex = date.year-MINYEAR;
    monthIndex = date.month-1;
    dayIndex = date.day-1;
    hourIndex = date.hour;
    minuteIndex = date.minute;
    
    NSArray *indexArray;
    
    if (self.datePickerStyle == EKDateStyleShowYearMonthDayHourMinute)
        indexArray = @[@(yearIndex),@(monthIndex),@(dayIndex),@(hourIndex),@(minuteIndex)];
    
    self.showYearView.text = _yearArray[yearIndex];
    
    [self.datePicker reloadAllComponents];
    
    for (int i = 0; i<indexArray.count; i++) {
        
        // 年
        if (i == 0)
            [self.datePicker selectRow:([indexArray[i] integerValue] + (kROWNUMBER / 2 + 1) * _yearArray.count / (kROWNUMBER + 1)) inComponent:i animated:animated];
        //月
        if (i == 1)
            [self.datePicker selectRow:([indexArray[i] integerValue] + (kROWNUMBER / 2 + 1) * _monthArray.count / (kROWNUMBER + 1)) inComponent:i animated:animated];
        
        // 日
        if (i == 2) {
            NSInteger rowInteger = ([indexArray[i] integerValue] + (kROWNUMBER / 2 + 1) * _dayArray.count / (kROWNUMBER + 1));
            [self.datePicker selectRow:rowInteger inComponent:i animated:animated];
        }
        
        // 时
        if (i == 3)
            [self.datePicker selectRow:([indexArray[i] integerValue] + (kROWNUMBER / 2 + 1) * _hourArray.count / (kROWNUMBER + 1)) inComponent:i animated:animated];
        // 分
        if (i == 4)
            [self.datePicker selectRow:([indexArray[i] integerValue] + (kROWNUMBER / 2 + 1) * _minuteArray.count / (kROWNUMBER + 1)) inComponent:i animated:animated];
    }
}


#pragma mark - getter / setter
-(UIPickerView *)datePicker {
    if (!_datePicker) {
        [self.showYearView layoutIfNeeded];
        _datePicker = [[UIPickerView alloc] initWithFrame:self.showYearView.bounds];
        _datePicker.showsSelectionIndicator = YES;
        _datePicker.delegate = self;
        _datePicker.dataSource = self;
    }
    return _datePicker;
}

-(void)setMinLimitDate:(NSDate *)minLimitDate {
    _minLimitDate = minLimitDate;
    if ([_scrollToDate compare:self.minLimitDate] == NSOrderedAscending) {
        _scrollToDate = self.minLimitDate;
    }
    [self getNowDate:self.scrollToDate animated:NO];
}

-(void)setThemeColor:(UIColor *)themeColor {
    _themeColor = themeColor;
    self.doneBtn.backgroundColor = themeColor;
    for (id subView in self.showYearView.subviews) {
        if ([subView isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)subView;
            label.textColor = themeColor;
        }
    }
}


-(void)setDatePickerStyle:(EKDatePickerStyle)datePickerStyle {
    _datePickerStyle = datePickerStyle;
    switch (datePickerStyle) {
            break;
        case EKDateStyleShowYearMonthDay:
        case EKDateStyleShowMonthDay:
            _dateFormatter = @"yyyy-MM-dd";
            break;
            
        default:
            break;
    }
    [self.datePicker reloadAllComponents];
}


@end
